package com.qf.jie.controller;

import com.qf.jie.controller.servlet.BaseServlet;
import com.qf.jie.entity.vo.RespBean;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/CheckController")
public class CheckController extends BaseServlet {
    protected void getCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.定义验证码的宽高
        int width = 100;
        int height = 50;
        //2.生成一个图片对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //3.获取画笔对象
        Graphics graphics = image.getGraphics();
        //4.选择画笔颜色
        graphics.setColor(Color.PINK);
        //5.填充背景颜色
        graphics.fillRect(0,0,width,height);
        //6.改变画笔颜色
        graphics.setColor(Color.BLUE);
        //7.选择字体和样式
        graphics.setFont(new Font("宋体",Font.BOLD,20));
        //8.生成随机数
        Random ran = new Random();
        String code;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            code = ran.nextInt(10)+"";
            sb.append(code);
            //9.添加随机数
            graphics.drawString(code,15+i*20,ran.nextInt(10)+30);
        }
        //把生成的随机验证码存放到 session 作用域中
        HttpSession session = req.getSession();
        session.setAttribute("serverCode",sb.toString());

        //10.改变画笔的颜色
        graphics.setColor(Color.YELLOW);
        //11.绘制干扰线
        for (int i = 0; i < 10; i++) {
            graphics.drawLine(ran.nextInt(width),ran.nextInt(height),ran.nextInt(width),ran.nextInt(height));
        }
        //12.把绘制好的验证码图像发给前端
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    protected RespBean checkCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端发送的数据
        String code = request.getParameter("code");
        String serviceCode = (String)request.getSession().getAttribute("serverCode");

        //2.判断验证码是否正确
        if(serviceCode!= null && serviceCode.equals(code)){
            return RespBean.respSuccess("验证码正确");
        }
        return RespBean.respError("验证码错误");
    }
}
